<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use addons\third\model\Third;
use think\Config;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("specTypeList", $this->model->getSpecTypeList());
    }
    public function randomkeys($length){
        $info="";
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';
        for($i=0;$i<$length;$i++) {
            $info .= $pattern{mt_rand(0,35)};    //生成php随机数
        }
            return $info;
    }
       

    protected function curl_url($url, $json)
    { 
        $body = json_encode($json);
        // return $body;
        $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
    

            /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            foreach ($list as $key => $value) {
                if(empty($value['goods_name'])){
                    $shoppingcar_array = json_decode($value['shoppingcar_id'],true);
                    $goods_list = Db::name('shoppingcar')->where('id','in',$shoppingcar_array)->select();
                    $list[$key]['goods_list'] = $goods_list;
                }
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    

    public function fahuo(){
        $order_id = input('ids');
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $order_data = Db::name('order')->where('id',$params['order_id'])->find();

                $update_order = [];
                $update_order['id'] = $params['order_id'];

                // 报价操作 order_status =50
               if($order_data['order_status']=='50'){
                
                    $update_order['order_status'] = '10';//待报价改为待支付

                    if(empty($order_data['goods_name'])){
                        $total_price = 0;
                        $thing1 = '';
                        $shoppingcar_array = json_decode($order_data['shoppingcar_id'],true);
                        $goods_list = Db::name('shoppingcar')->where('id','in',$shoppingcar_array)->select();
                        foreach ($goods_list as $key => $value) {
                            $now_price = $value['num']*$params['unit_price'][$key];
                            $total_price += $now_price;

                            Db::name('shoppingcar')->where('id',$value['id'])->update(['total_price'=>$now_price,'unit_price'=>$params['unit_price'][$key]]);

                        }
                        $thing1 = $goods_list[0]['goods_name'].'等商品';

                    }else{
                        $total_price = $order_data['num']*$params['unit_price'];

                        $update_order['unit_price'] = $params['unit_price'];
                        $thing1 = $order_data['goods_name'];
                    }

                    $update_order['total_price'] = $total_price+$order_data['fee'];
                    $update_order['baojia_time'] = time();


               }else{
                    if(empty($order_data['goods_name'])){
                        $thing1 = '';
                        $shoppingcar_array = json_decode($order_data['shoppingcar_id'],true);
                        $goods_list = Db::name('shoppingcar')->where('id','in',$shoppingcar_array)->select();
                        $thing1 = $goods_list[0]['goods_name'].'等商品';
                    }else{
                        $thing1 = $order_data['goods_name'];
                    }

                    // 自己提货
                    if($order_data['delivery_methods']=='20'&&$order_data['order_status']=='20'){

                        if($order_data['code'])$this->error('提货码已经存在');

                        if($order_data['order_status']=='10')$this->error('该订单未支付');

                        
                        $update_order['id'] = $order_data['id'];
                        $update_order['delivery_time'] = time();
                        $update_order['order_status'] = 30;
                        // 订单状态:10=未支付,20=已支付待发货,30=已发货,40=确认收货 
                        $update_order['code'] = self::randomkeys(6);

                        $up_res = Db::name('order')->update($update_order);
                        if($up_res)$this->success('发货成功');  
                        
                    }else if($order_data['delivery_methods']=='20'&&$order_data['order_status']=='30'){
                        // 确认提货
                        $update_order['order_status'] = 40;
                    }else{
                        //物流公司发货
                        $update_order['order_status'] = 30;
                        $update_order['company'] = $params['company'];
                        $update_order['track_number'] = $params['track_number'];
                        $update_order['id'] = $order_data['id'];

                    }
                    

               }
$res = Db::name('order')->update($update_order);
                        if($res)$this->success('操作成功');  
                              
            }else{
                $this->error(__('Parameter %s can not be empty', ''));
            }
            
        }

        $list = $this->model
            ->with('user')
            ->with('mendian')
            ->find($order_id);

        $list = $list->toArray();
        $list['address'] = Db::name('address')->where('id',$list['address_id'])->find();
        $area_id = $list['address']['area_id'];
        if(empty($area_id))$this->error('请重新修改收货信息');

        if(empty($list['goods_name'])){
            $shoppingcar_array = json_decode($list['shoppingcar_id'],true);
            $goods_list = Db::name('shoppingcar')->where('id','in',$shoppingcar_array)->select();
            $list['goods_list'] = $goods_list;
            
            if($list['fee']=='0.00'){// 多商品时候计算运费
                $total_fee = 0;
                foreach ($list['goods_list'] as $key => $value) {
                   $fee = 0;  
                      
                   $goods = Db::name('litestore_goods')->where('goods_id',$value['goods_id'])->field('litestore_freight_id,zhongliang')->find();
                   if(empty($goods['zhongliang']))$this->error('该商品重量为空，请修改');
                   if(empty($goods['litestore_freight_id']))$this->error('该商品无快递模板，请修改');

                   $method = Db::name('litestore_freight')->where('id',$goods['litestore_freight_id'])->value('method');//是按重量还是数量
                   
                   $where['litestore_freight_id'] = $goods['litestore_freight_id'];
                   $where[] = ['exp',Db::raw("FIND_IN_SET($area_id,region)")]; 
                  
                   $fee_rule = Db::name('litestore_freight_rule')->where($where)->find();
                    if(empty($fee_rule))$this->error('没有该地区的运费模板');
                   if($method==10){//按件数
                    
                        if($value['num'] > $fee_rule['first']){
                            $shengyu_num = $value['num']-$fee_rule['first'];
                            $shengyu_fee = ceil($shengyu_num/$fee_rule['additional'])*$fee_rule['additional_fee'];

                            $fee = $fee_rule['first_fee']+$shengyu_fee;
                        }else{
                            //最低件数标准的运费
                            $fee = $fee_rule['first_fee'];
                        }
                   }else{//按重量
                        $zhongliang_sum = $goods['zhongliang']*$value['num'];
                        if($zhongliang_sum>=$fee_rule['first']){
                            $shengyu_zl = $zhongliang_sum-$fee_rule['first'];
                            if($fee_rule['additional']==0){
                                $this->error('该快递模板的值有零请查看');
                            }
                            $shengyu_fee = ceil($shengyu_zl/$fee_rule['additional'])*$fee_rule['additional_fee'];

                            $fee += $fee_rule['first_fee']+$shengyu_fee;
                        }else{
                            //最低重量标准的运费
                            $fee = $fee_rule['first_fee'];
                        }
                        $list['goods_list'][$key]['zhongliang'] = $zhongliang_sum;
                   }
                    $list['goods_list'][$key]['fee'] = $fee;
                    $list['goods_list'][$key]['zhongliang'] = $zhongliang_sum;
                    Db::name('shoppingcar')->where('id',$value['id'])->update(['fee'=>$fee,'zhongliang'=>$zhongliang_sum]);   
                    $total_fee += $fee;   

                }//循环多商品
                $list['fee'] = $total_fee;

              Db::name('order')->where('id',$order_id)->update(['fee'=>$total_fee,'total_price'=>$total_fee+$list['total_price']]);
            }
        }else{
            // halt($list);
            // 单商品时候计算运费
            if($list['fee']=='0.00'){
               $goods = Db::name('litestore_goods')->where('goods_id',$list['goods_id'])->field('litestore_freight_id,zhongliang')->find();
               if(empty($goods['zhongliang']))$this->error('该商品重量为空，请修改');
               if(empty($goods['litestore_freight_id']))$this->error('该商品无快递模板，请修改');

               $method = Db::name('litestore_freight')->where('id',$goods['litestore_freight_id'])->value('method');
               
               $where['litestore_freight_id'] = $goods['litestore_freight_id'];
               $where[] = ['exp',Db::raw("FIND_IN_SET($area_id,region)")]; 
               $fee_rule = Db::name('litestore_freight_rule')->where($where)->find();
               $fee = 0;
               if(empty($fee_rule))$this->error('没有该地区的运费模板');

               if($method==10){//按件数
                
                    if($list['num']>=$fee_rule['first']){
                        $shengyu_num = $list['num']-$fee_rule['first'];
                        if($fee_rule['additional']==0){
                                $this->error('该快递模板的值有零请查看');
                            }
                        $shengyu_fee = ceil($shengyu_num/$fee_rule['additional'])*$fee_rule['additional_fee'];

                        $fee = $fee_rule['first_fee']+$shengyu_fee;
                    }else{
                        //最低件数标准的运费
                        $fee = $fee_rule['first_fee'];
                    }
               }else{//按重量
                    $zhongliang_sum = $goods['zhongliang']*$list['num'];

                    if($zhongliang_sum>=$fee_rule['first']){
                        $shengyu_zl = $zhongliang_sum-$fee_rule['first'];
                        $shengyu_fee = ceil($shengyu_zl/$fee_rule['additional'])*$fee_rule['additional_fee'];

                        $fee = $fee_rule['first_fee']+$shengyu_fee;
                    }else{
                        //最低重量标准的运费
                        $fee = $fee_rule['first_fee'];
                    }
                    $list['zhongliang'] = $zhongliang = $zhongliang_sum;
               }
               if(empty($list['zhongliang'])){
                $zhongliang = 0;
               }
               $list['fee'] = $fee;
               
               Db::name('order')->where('id',$list['id'])->update(['fee'=>$fee,'zhongliang'=>$zhongliang,'total_price'=>$fee+$list['total_price']]);
            }
        }// 单商品时候计算运费
        $this->view->assign("order_id", $order_id);
        $this->view->assign("data", $list);

        return $this->view->fetch();
    }
        protected function sendSubMessage($params,$token){
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$token;
        $re = $this->curl_url($url,$params);
        return $re;
    }
    protected function getAccessToken()
    {
      //当前时间戳
      $now_time = time();

      //失效时间
      $timeout = 7200 ;

      //判断access_token是否过期
      $before_time = $now_time - $timeout;

      //未查找到就为过期
      $access_token = Db::name('access_token')
        ->where('createtime' ,'>',$before_time)
        ->value('access_token');

      if(empty($access_token)){
        $config = get_addon_config('epay');

        $appId= $config['wechat']['miniapp_id'];// 小程序 APPID
        $appSecret = $config['wechat']['app_secret'];//小程序密钥
        $r = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret"); //返回的是字符串，需要用json_decode转换成数组
        $data = json_decode($r,true);
        Db::name('access_token')->insert(['access_token'=>$data['access_token'],'createtime'=>$now_time]);
        return $data['access_token'];
      }
      return $access_token;
      
    }


}
